package net.zwj.aio;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class AcceptCompletionHandler implements
		CompletionHandler<AsynchronousSocketChannel, Object> {

	private AsynchronousServerSocketChannel serverSocketChannel;

	public AcceptCompletionHandler(
			AsynchronousServerSocketChannel serverSocketChannel) {
		this.serverSocketChannel = serverSocketChannel;
	}

	private void pendingAccept() {
		if (this.serverSocketChannel.isOpen()) {
			this.serverSocketChannel.accept(null, new AcceptCompletionHandler(
					serverSocketChannel));

		} else {
			throw new IllegalStateException("Controller has been closed");
		}
	}

	@Override
	public void completed(AsynchronousSocketChannel socketChannel, Object attachment) {
		try {  
            System.out.println("Accept connection from "  
                    + socketChannel.getRemoteAddress());  
            ByteBuffer echoBuffer = ByteBuffer.allocate(1024);
            echoBuffer.clear();  
            socketChannel.read(echoBuffer).get();  
            echoBuffer.flip();  
            // echo data  
            socketChannel.write(echoBuffer);  
            echoBuffer.flip();  
            System.out.println("done...");
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            pendingAccept(); 
        }  

	}

	@Override
	public void failed(Throwable exc, Object attachment) {
		System.err.println("accept error!");
		exc.printStackTrace();
		pendingAccept();
	}

}
